package com.xunqi.crm.service.impl;

import com.xunqi.crm.pojo.Role;
import com.xunqi.crm.pojo.User;
import com.xunqi.crm.repository.UserRepository;
import com.xunqi.crm.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    @Override
    public User login(String usrName, String usrPassword) {
        return userRepository.findByUsrNameAndUsrPassword(usrName, usrPassword);
    }

    @Override
    public void saveUser(User user) {
        userRepository.save(user);
    }

    @Override
    public void deleteUser(Long usrId) {
        userRepository.deleteById(usrId);
    }

    @Override
    public User getUser(Long usrId) {
        return userRepository.getOne(usrId);
    }

    @Override
    public Page<User> findUsers(String usrName, Long roleId, Pageable pageable) {
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (usrName != null && !usrName.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("usrName"), "%" + usrName + "%"));
                }
                if (roleId != null && roleId.longValue() != 0l) {
                    Role role = new Role();
                    role.setRoleId(roleId);
                    predicates.add(criteriaBuilder.equal(root.get("role"), role));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return userRepository.findAll(specification, pageable);
    }

    @Override
    public User getUser(String usrName) {
        return userRepository.findUserByUsrName(usrName);
    }

}
